<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <link rel="stylesheet" type="text/css" href="./lib/bootstrap.css" />
</head>

<body>
    <form id="myform">
        <input type="file" name="myfile" id="myfile" />
        <input type="button" value="提交" id="btn" />
    </form>
    <div>
        <img src="" id="test" />
    </div>
    <!-- bootstrap 中的进度条 -->
    <div class="progress" style="width: 500px; margin: 15px 10px;">
        <div class="progress-bar progress-bar-striped active" style="width: 0%;" id="percent">
            0%
        </div>
    </div>
    <script type="text/javascript">
        var btn = document.getElementById("btn");
        btn.onclick = function() {
            // 1.var myfile = document.getElementById("myfile").files[0];
            //files是input:file的内容其是一个伪数组
            //1. if (!myfile) {
            //     alert("请选择文件");
            //     return;
            // }
            // 1.var fd = new FormData();
            // 1.fd.append("avater", myfile);
            var form = document.getElementById("myform");
            var fd = new FormData(form);

            var xhr = new XMLHttpRequest();
            xhr.upload.onprogress = function(e) {
                if (e.lengthComputable) {
                    var num = Math.ceil((e.loaded / e.total) * 100);
                    console.log(num);
                    var percent = document.getElementById("percent");
                    percent.style = "width:" + num + "%";
                    percent.innerHTML = num + "%";
                }
            };
            xhr.upload.onload = function(e) {
                var percent = document.getElementById("percent");
                percent.classList.remove("progress-bar-striped", "active");
                percent.classList.add("progress-bar-success");
            };
            xhr.open("post", "http://www.liulongbin.top:3006/api/upload/avatar");
            xhr.send(fd);
            xhr.onreadystatechange = function() {
                if ((xhr.readyState == 4) & (xhr.status === 200)) {
                    var ret = xhr.responseText;
                    ret = JSON.parse(ret);
                    var img = document.getElementById("test");
                    img.setAttribute("src", "http://www.liulongbin.top:3006" + ret.url);
                }
            };
        };
    </script>
</body>

</html>